var param = {}, formId = 'queryForm', url = "/openx/order/supplyPresOrderService/listPage", orderDetail = {};

var days = 30;

//查询按钮触发
$.openx.query = function () {
    //查询验证时间区间
    var createStartTime = new Date($("#startTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#endTime").val().replace(/\-/g, "\/"));
    if (isNaN(createStartTime.getTime())) {
        layer.msg('开始时间不能为空！');
        return false;
    }
    if (isNaN(createEndTime.getTime())) {
        layer.msg('结束时间不能为空！');
        return false;
    }
    if (createStartTime > createEndTime) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    refreshTable();
}

function refreshTable() {
    var data = $.openx.getJsonObj(formId);
    data.timeRange = {
        startTime: data.startTime,
        endTime: data.endTime
    }
    param.supplyPres = data;
    var equryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
}

function reviewSuccess() {
    var arrays = $.openx.getSelectedRow();
    if (arrays.length === 0) {
        layer.msg("请选择订单！");
        return;
    }
    layer.confirm('是否确定该订单进行补方！！！', {
        btn: ['确认','取消'] //按钮
    }, function(){
        var orderCodes = [];
        for (var i = 0; i < arrays.length; i++) {
            var row = arrays[i];
            orderCodes.push(row.orderCode);
        }
        $X("/order/supplyPresOrderService", "reviewSuccess").callx({
            orderCodes : orderCodes,
            onResult : function(data) {
                if(data && data.length > 0) {
                    layer.msg("订单处理失败！订单号如下：" + data);
                }
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError : function(error) {
                var res = JSON.parse(error);
                layer.msg(res.message);
            }
        }, 60*1000);
    }, function () {
        layer.closeAll();
    });
}

function reviewFailure() {
    var arrays = $.openx.getSelectedRow();
    if (arrays.length === 0) {
        layer.msg("请选择订单！");
        return;
    }
    layer.confirm('是否拒绝补方，拒绝补方后订单将被取消', {
        btn: ['确认','取消'] //按钮
    }, function(){
        var orderCodes = [];
        for (var i = 0; i < arrays.length; i++) {
            var row = arrays[i];
            orderCodes.push(row.orderCode);
        }
        $X("/order/supplyPresOrderService", "reviewFailure").callx({
            orderCodes : orderCodes,
            onResult : function(data) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError : function(error) {
                var res = JSON.parse(error);
                layer.msg(res.message);
            }
        }, 60*1000);
    }, function () {
        layer.closeAll();
    });
}

//初始化时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    var createStartTime = laydate.now(-1) + ' 00:00:00';
    var createEndTime = laydate.now() + ' 23:59:59';
    document.getElementById('startTime').value = createStartTime;
    document.getElementById('endTime').value = createEndTime;

    var data = $.openx.getJsonObj(formId);
    data.timeRange = {
        startTime: createStartTime,
        endTime: createEndTime
    }
    param.supplyPres = data;
    $.openx.initTable("table", url, param);
});

function resetForm() {
    $('#queryForm')[0].reset();
    $('#channelSelectsId').val(null).trigger('change');
    var laydate = layui.laydate;
    var createStartTime = laydate.now(-1) + ' 00:00:00';
    var createEndTime = laydate.now() + ' 23:59:59';
    document.getElementById('startTime').value = createStartTime;
    document.getElementById('endTime').value = createEndTime;
    start.max = '2099-06-16';
    start.min = '1900-01-01';
    end.max = '2099-06-16';
    end.min = '1900-01-01';
    var data = $.openx.getJsonObj(formId);
    data.timeRange = {
        startTime: createStartTime,
        endTime: createEndTime
    }
    param.supplyPres = data;
    $.openx.initTable("table", url + "?t=" + new Date().getTime(), param);
}


//查看订单详情
function showOrderDetail(row) {
    var html = $.openx.innerHtml('orderDetailTpl')
    $X("/order/queryService", "getOrderDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            layer.closeAll('loading')
            result.coupon = false;
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver
            result.createTime = $.openx.formatDate(new Date(result.createTime))
            if (receiver) {
                result.receiverName = receiver.name
                result.receiverPhone = receiver.phone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "")
            }

            var additionalInfos = result.additionalInfos
            for (let i = 0; i < additionalInfos.length; i++) {
                if (additionalInfos[i].infoCode === 'couponSn'){
                    result.coupon = true;
                }
            }
            laytpl($.openx.innerHtml('orderDetailTpl')).render(result, function (html) {
                $.openx.openLayer(null, '订单详情', html, true)
            });


            //当前订单详细对象
            orderDetail = result;
            console.log(result);
        },
        onError: function (error) {

        }
    });
}

//*****************格式化代码**********************/
//格式化下单时间
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value));
}

/**
 * 格式化查看订单详情
 */
function showOrderDetailFormat(value, row) {
    return "<a href=\'javascript:void(0)\' title='\点击查看订单详情\' style = '\color:#000000;text-decoration:underline;\' onclick =\'javascript:showOrderDetail(" + JSON.stringify(row) + ")\'><b>" + row.orderCode + "</b><a>";
}

function supplyPresStatusFormat(value, row) {
    switch (value) {
        case "PENDING":
            return "待审核";
        case "REVIEW_SUCCESS":
            return "审核成功";
        case "REVIEW_FAILURE":
            return "审核失败";
        default:
            return value;
    }
}

function showAll(row) {
    layer.tips(row.remark, '#table a[id="' + row.orderCode + '"]', {
        tips: [4, '#78BA32'],
        area: ['auto', 'auto']
    });
}

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

function formatCode(value, row) {
    if (value && value !== '000000') {
        return '\'' + value;
    } else {
        return '';
    }
}


function showRecipe(topChannelCode) {
    if (topChannelCode === 'PAHYS' || topChannelCode === 'PABC' || topChannelCode === 'DSJK' || topChannelCode === 'KWZY'|| topChannelCode === 'XLYG' || topChannelCode === 'NEB' || topChannelCode === 'FXJK' || topChannelCode === 'FXJKBC') {
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".pdf";
        window.location.href = url;
    }else if(topChannelCode === 'JDDJ'  || topChannelCode === 'YYW'){
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".jpg";
        window.location.href = url;
    } else if(topChannelCode === 'XRQEYS' || topChannelCode === 'XINGREN'){
        if (orderDetail.ordonnanceId != undefined) {
            var url = ecp_boss_logistics_tpl_url+"/html/order/prescriptionDetail.html?prescriptionId=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        } else {
            if (orderDetail.prescriptFileIsExist === 'Y') {
                var url = ecp_boss_logistics_tpl_url+"/html/order/prescriptionDetail.html?prescriptionId=" + orderDetail.ordonnanceId;
                loodPrescript(url);
            }
        }
    } else if (topChannelCode === 'YFJX' || topChannelCode === 'ZHEBOTO' || topChannelCode === 'JDYJS' || topChannelCode === 'JDYJSBC'|| topChannelCode === 'YSQYJK' || topChannelCode === 'YSQYJKBC'|| topChannelCode === 'JKXB' || topChannelCode === 'YFYS' || topChannelCode === 'XR') {
        if (orderDetail.ordonnanceId !== undefined) {
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    } else{
        if (orderDetail.ordonnanceId != undefined) {
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    }
}

function loodPrescript(url){
    layer.open({
        content: [url],
        type: 2,
        title: '查看处方',
        area: ['1000px', '500px']
    });
}

var start = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        end.min = datas; //开始日选好后，重置结束日的最小日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth() + 1)
        date.setDate(new Date(date.getDate() + (days - 1)));
        end.max = DateToStr(date, 'max');

    }
};
var end = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        start.max = datas; //结束日选好后，重置开始日的最大日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth());
        days = days > date.getDate() ? days : date.getDate();
        date.setDate(new Date(date.getDate() - (days - 1)));
        start.min = DateToStr(date, 'min');
    }
};

$("#startTime").on("click", function () {
    start.elem = this;
    laydate(start);
});
$("#endTime").on("click", function () {
    end.elem = this;
    laydate(end);
});

function DateToStr(date, flag) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString();
    var day = (date.getDate()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
    dateTime = year + "-" + month + "-" + day;
    return dateTime;
}

//获取当前月多少天
function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month == '1' || month == '3' || month == '5' || month == '7' || month == '8' || month == '10' || month == '12') {
        monthDays = 31;
    } else if (month == '4' || month == '6' || month == '9' || month == '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

//乘法函数
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    // alert(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

/**
 * 格式化备注

 */
function remarkFormat(value, row) {
    if (row.remark) {
        if (row.remark.length > 10) {
            return "<a id='" + row.orderCode + "' onclick='showAll(" + JSON.stringify(row) + ");'>" + row.remark.substring(0, 10) + "\n..." + "</a>";
        } else {
            return row.remark;
        }
    }
    return "-";
}